//
//  KZSlideLabel.swift
//  Fanrengame
//
//  Created by 朱凯 on 2018/4/18.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import UIKit

class KZSlideLabel: UILabel {
    
    convenience init() {
        self.init(frame: .zero)
        self.textColor = .clear
    }
    
    var timer: DispatchSourceTimer!
    var color: UIColor = kThemeColor
    
    var isSlideOver: Bool {
        get {
            return timer.isCancelled
        }
    }
    override var textColor: UIColor! {
        didSet {
            if textColor != .clear {
                self.color = textColor
                self.textColor = .clear
            }
        }
    }
    override var text: String? {
        didSet {
            timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
            let attrStr = NSMutableAttributedString.init(string: text!)
            var tag = 0
            timer.schedule(deadline: DispatchTime.now(), repeating: 0.1)
            timer.setEventHandler(handler: {
                tag+=1
                for i in 0..<attrStr.length {
                    attrStr.setAttributes([NSAttributedStringKey.foregroundColor : self.color.withAlphaComponent(CGFloat(tag - i)/10.0)], range: NSRange.init(location: i, length: 1))
                }
                self.attributedText = attrStr
                if tag >= attrStr.length + 9 {
                    self.timer.cancel()
                    return
                }
            })
            timer.resume()
        }
    }
    
    func overSoon() {
        self.timer.cancel()
        let attrStr = NSMutableAttributedString.init(string: text!)
        attrStr.setAttributes([NSAttributedStringKey.foregroundColor : color], range: NSRange.init(location: 0, length: self.text!.count))
        self.attributedText = attrStr
    }
}
